<?php
/**
 * DownGoods.php class file.
 * @author wudg <544038230@qq.com>
 * @date 2020/12/27- 下午5:40
 */

namespace common\jobs\sync;


use common\constants\ProductConst;
use common\dao\PddCopyProductsDao;
use common\models\PddMallProductSkus;
use common\models\PddMallProduct;
use common\components\api\isv\Goods;
use common\exception\TaskException;
use console\components\helpers\ConsoleHelper;
use common\constants\SyncConst;
use common\dao\PddSyncLogDao;
use common\dao\PddSyncBatchLogDao;
use common\exception\ServiceException;
use common\exception\ValidatorException;
use common\services\SyncProductbatchDetailService;
use yii\db\Exception;
use common\services\MallProductService;
use Yii;

class SyncGoodsToSyncbatchdetail extends SyncBase implements \common\drivers\interfaces\JobInterface
{
    public $args = [];

    /**
     * 复制数据
     * @var array
     */
    public $copyData = [];

    /**
     * 获取异步任务执行需要的参数
     * SyncProduct constructor.
     * @param array $args
     */
    public function __construct(array $args = [])
    {
        $this->args = $args;

        $this->cacheSuccessKey .= ('batch' . $this->args['batch_log_id']);
        $this->cacheErrorKey .= ('batch' . $this->args['batch_log_id']);
        $this->totalCacheKey .= ('batch' . $this->args['batch_log_id']);
    }


    /**
     * 处理队列
     * @return mixed|void
     */
    public function handle() :void
    {
        try {
            Yii::$app->db->open();
            //任务信息
            $syncBatchLogDao = new PddSyncBatchLogDao();
            $batchInfo = $syncBatchLogDao->getLastLogInfo($this->args['batch_log_id']);
            //商品信息
            if (!$this->args['goods_id']) {
                throw new TaskException('商品不存在');
            }
            $goodsDetail = PddMallProduct::find()
                ->where(['mall_id' => $this->args['mall_id'], 'goods_id' => $this->args['goods_id']])
                ->one()->toArray();
            if (!$goodsDetail) {
                $syncLog = (new PddSyncBatchLogDao())->getInfoByPkProducts($this->args['batch_log_id'], $this->args['uid'], $this->args['mall_id'], $this->args['goods_id']);
                $syncLog->updated_at = time();
                $syncLog->error_info = '商品不存在';
                $syncLog->status = 3;
                $syncLog->save();
                $this->setErrorNum();
                throw new TaskException('商品不存在');
            }
            $result = (new SyncProductbatchDetailService())->copy($goodsDetail, $batchInfo, 1);
            if(isset($result['error_info'])){
                if($result['error_info'] == '商品已删除'){
                    $result['error_code'] = 3;
                }
            }
            $this->saveLog($result);
            Yii::$app->db->close();
        } catch (\yii\base\Exception $e) {
            $syncLog = (new PddSyncBatchLogDao())->getInfoByPkProducts($this->args['batch_log_id'], $this->args['uid'], $this->args['mall_id'], $this->args['goods_id']);
            $syncLog->updated_at = time();
            $syncLog->error_info = substr($e->getMessage(), 0, 240);
            $syncLog->status = 2;
            $syncLog->save();
            $this->setErrorNum();
            throw new TaskException($e->getMessage());
        } finally {
            Yii::$app->db->close();
        }
    }

    /**
     * @throws \yii\base\Exception
     */
    protected function setSuccessNum()
    {
        $cacheSuccessNum = Yii::$app->redis->get($this->cacheSuccessKey);
        if (!$cacheSuccessNum) {
            Yii::$app->redis->setex($this->cacheSuccessKey, 86400, 1);
        } else {
            Yii::$app->redis->incr($this->cacheSuccessKey);
        }
        $this->upsetBatchInfo();
    }

    protected function getSuccessNum()
    {
        return Yii::$app->redis->get($this->cacheSuccessKey);
    }


    /**
     * @throws \yii\base\Exception
     */
    protected function setErrorNum()
    {
        $cacheErrorNum = Yii::$app->redis->get($this->cacheErrorKey);
        if (!$cacheErrorNum) {
            Yii::$app->redis->setex($this->cacheErrorKey, 86400, 1);
        } else {
            Yii::$app->redis->incr($this->cacheErrorKey);
        }
        $this->upsetBatchInfo();
    }


    protected function getErrorNum()
    {
        return Yii::$app->redis->get($this->cacheErrorKey);
    }


    /**
     * @throws \yii\base\Exception
     */
    protected function upsetBatchInfo()
    {
        $successNum = (int)$this->getSuccessNum();
        $errorNum = (int)$this->getErrorNum();
        $totalNum = $successNum + $errorNum;
        $total_cnt = Yii::$app->redis->get($this->totalCacheKey);
        if ($totalNum == $total_cnt) {

            $syncLog = (new PddSyncBatchLogDao())->getInfoByPk($this->args['batch_log_id']);
            $syncLog->success_cnt = $successNum;
            $syncLog->fail_cnt = $errorNum;
            $syncLog->status = SyncConst::SYNC_STATUS_YES;
            $syncLog->save();
            Yii::$app->redis->del($this->cacheErrorKey);
            Yii::$app->redis->del($this->totalCacheKey);
            Yii::$app->redis->del($this->cacheSuccessKey);
        }
    }

    public function saveLog(array $results = []){
        if($results){
            if (isset($results['error_code'])) {
                //失败
                $getUpdateResult = $this->getSaveInfo($results['updateInfo'][0]);
                (new MallProductService())->updateGoodsUpdateEdit($this->args['goods_id'], $getUpdateResult['before'], $getUpdateResult['after'],$results['error_code'],0,$this->args['uid'],$this->args['mall_id'],$this->args['batch_log_info_id'],$results['error_info']);
                $this->setErrorNum();
            }else{
                //同步成功日志表
                if (isset($results['updateInfo'])) {
                    $getUpdateResult = $this->getSaveInfo($results['updateInfo'][0]);
                    (new MallProductService())->updateGoodsUpdateEdit($this->args['goods_id'], $getUpdateResult['before'], $getUpdateResult['after'],1,0,$this->args['uid'],$this->args['mall_id'],$this->args['batch_log_info_id']);
                }
                $this->setSuccessNum();
            }
        }else {
            $this->setErrorNum();
        }
    }

    public function getSaveInfo(array $result = []){
        $before = array();
        $after = array();
        if (isset($result['new_goods_name'])) {
            if (isset($result['goods_name'])) {
                $before['goods_name'] = $result['goods_name'];
            }
            $after['goods_name'] = $result['new_goods_name'];
        }
        if (isset($result['newstatus'])) {
            if (isset($result['status'])) {
                $before['status'] = $result['status'];
            }
            $after['status'] = $result['newstatus'];
        }
        if (isset($result['new_tiny_name'])) {
            if (isset($result['tiny_name'])) {
                $before['tiny_name'] = $result['tiny_name'];
            }
            $after['tiny_name'] = $result['new_tiny_name'];
        }
        if (isset($result['new_is_pre_sale'])) {
            if (isset($result['is_pre_sale'])) {
                $before['is_pre_sale'] = $result['is_pre_sale'];
            }
            $after['is_pre_sale'] = $result['new_is_pre_sale'];
        }
        //预售时间
        if (isset($result['new_presaletime'])) {
            if (isset($result['pre_sale_time'])) {
                $before['pre_sale_time'] = $result['pre_sale_time'];
            }
            $after['pre_sale_time'] = $result['new_presaletime'];
        }

        //运费模版
        if (isset($result['new_cost_template_id'])) {
            if (isset($result['cost_template_id'])) {
                $before['cost_template_id'] = $result['cost_template_id'];
                $before['cost_template_name'] = $result['cost_template_name'];
            }
            $after['cost_template_id'] = $result['new_cost_template_id'];
            $after['cost_template_name'] = $result['new_cost_template_name'];
        }
        //服务承诺
        //运费模版
        if (isset($result['new_is_folt'])) {
            if (isset($result['is_folt'])) {
                //if(($result['is_folt'] == 'true'&&$result['new_is_folt'] == 0)||($result['is_folt'] == 'false'&&$result['new_is_folt'] == 1)){
                $before['is_folt'] = ($result['is_folt'] == 'true'?1:0);
                $after['is_folt'] =$result['new_is_folt'];
                //}
            }
        }
        if (isset($result['new_is_refundable'])) {
            if (isset($result['is_refundable'])) {
                //if(($result['is_refundable'] == 'true'&&$result['new_is_refundable'] == 0)||($result['is_refundable'] == 'false'&&$result['new_is_refundable'] == 1)){
                $before['is_refundable'] = ($result['is_refundable'] == 'true'?1:0);
                $after['is_refundable'] =$result['new_is_refundable'];
                //}
            }
        }
        if (isset($result['new_second_hand'])) {
            if (isset($result['second_hand'])) {
                //if(($result['second_hand'] == 'true'&&$result['new_second_hand'] == 0)||($result['second_hand'] == 'false'&&$result['new_second_hand'] == 1)){
                $before['second_hand'] = ($result['second_hand'] == 'true'?1:0);
                $after['second_hand'] =$result['new_second_hand'];
                //}
            }
        }
        //有无物流方式
        if (isset($result['new_delivery_type'])) {
            if (isset($result['delivery_type'])) {
                //if(($result['second_hand'] == 'true'&&$result['new_second_hand'] == 0)||($result['second_hand'] == 'false'&&$result['new_second_hand'] == 1)){
                $before['delivery_type'] = $result['delivery_type'];
                $after['delivery_type'] =$result['new_delivery_type'];
                //}
            }
        }

        if (isset($result['new_shipment_limit_second'])) {
            if (isset($result['shipment_limit_second'])) {
                //if($result['new_shipment_limit_second'] <> $result['shipment_limit_second']){
                $before['shipment_limit_second'] =$result['shipment_limit_second'];
                $after['shipment_limit_second'] =$result['new_shipment_limit_second'];
                //}
            }
        }
        if (isset($result['new_customer_num'])) {
            if (isset($result['customer_num'])) {
                //if($result['new_customer_num'] <> $result['customer_num']){
                $before['customer_num'] =$result['customer_num'];
                $after['customer_num'] =$result['new_customer_num'];
                //}
            }
        }
        if (isset($result['new_order_limit'])) {
            if (isset($result['order_limit'])) {
                //if($result['new_order_limit'] <> $result['order_limit']){
                $before['order_limit'] =$result['order_limit'];
                $after['order_limit'] =$result['new_order_limit'];
                //}
            }
        }
        if (isset($result['new_buy_limit'])) {
            if (isset($result['buy_limit'])) {
                //if($result['new_buy_limit'] <> $result['buy_limit']){
                $before['buy_limit'] =$result['buy_limit'];
                $after['buy_limit'] =$result['new_buy_limit'];
                //}
            }
        }


        return array(
            'before' => $before,
            'after' => $after
        );
    }

}